package com.hongsuan.pplive.mobileAPI.utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

import com.cnjson.common.utils.HttpUtil;

public class AppHttpUpload {

	private static final int TIME_OUT = 10 * 10000000; // 超时时间
	private static final String CHARSET = "utf-8"; // 设置编码
	public static final String SUCCESS = "1";
	public static final String FAILURE = "0";
	// private static final String UPLOAD_API =
	// "http://119.29.166.150/v2/file/upload";

	private static final String UPLOAD_API = "http://127.0.0.1:8080/pplive/v2/user/uploadPhoto";

	public static String uploadFile(File file, String userId) {
		String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
		String PREFIX = "--", LINE_END = "\r\n";
		String CONTENT_TYPE = "multipart/form-data"; // 内容类型
		String RequestURL = UPLOAD_API + "?userId=" + userId;
		try {
			URL url = new URL(RequestURL);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(TIME_OUT);
			conn.setConnectTimeout(TIME_OUT);
			conn.setDoInput(true); // 允许输入流
			conn.setDoOutput(true); // 允许输出流
			conn.setUseCaches(false); // 不允许使用缓存
			conn.setRequestMethod("POST"); // 请求方式
			conn.setRequestProperty("Charset", CHARSET); // 设置编码
			conn.setRequestProperty("connection", "keep-alive");
			conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
			if (file != null) {
				/**
				 * 当文件不为空，把文件包装并且上传
				 */
				OutputStream outputSteam = conn.getOutputStream();
				DataOutputStream dos = new DataOutputStream(outputSteam);
				StringBuffer sb = new StringBuffer();
				sb.append(PREFIX);
				sb.append(BOUNDARY);
				sb.append(LINE_END);

				/**
				 * 这里重点注意： name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
				 * filename是文件的名字，包含后缀名的 比如:abc.png
				 */

				sb.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\""
						+ LINE_END);
				sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END);
				sb.append(LINE_END);
				dos.write(sb.toString().getBytes());
				InputStream is = new FileInputStream(file);
				byte[] bytes = new byte[1024];
				int len = 0;
				while ((len = is.read(bytes)) != -1) {
					dos.write(bytes, 0, len);
				}
				is.close();
				dos.write(LINE_END.getBytes());
				byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
				dos.write(end_data);
				dos.flush();
				/**
				 * 获取响应码 200=成功 当响应成功，获取响应的流
				 */
				int res = conn.getResponseCode();
				if (res == 200) {
					// System.out.println("return path=" +
					// conn.getHeaderField("file"));
					System.out.println("return result" + getInputStream(conn));
					return SUCCESS;
				}
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return FAILURE;
	}

	/**
	 * get response data from request(POST method) we must commit (encode is
	 * utf-8)
	 * 
	 * @param conn
	 * @throws IOException
	 */
	public static String getPostData(HttpURLConnection conn, Map<String, String> paramMap) throws IOException {
		// setup for post method
		conn.setDoInput(true);
		conn.setDoOutput(true);
		conn.setRequestMethod("POST");
		conn.setUseCaches(false);
		conn.setInstanceFollowRedirects(true);
		conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		conn.connect();

		// if parameter list is not empty, we must commit (encode is utf-8)
		if ((paramMap != null) && (!paramMap.isEmpty())) {
			DataOutputStream out = new DataOutputStream(conn.getOutputStream());
			String paramString = "";
			for (Iterator<String> iter = paramMap.keySet().iterator(); iter.hasNext();) {
				String param = iter.next();
				String value = URLEncoder.encode(paramMap.get(param), CHARSET);
				paramString += (param + "=" + value);
				if (iter.hasNext())
					paramString += "&";
			}
			out.writeBytes(paramString);
			out.flush();
			out.close();
		}
		return getInputStream(conn);
	}

	private static String getInputStream(HttpURLConnection conn) throws IOException {
		StringBuilder data = new StringBuilder();
		BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		String inputLine = "";
		while ((inputLine = reader.readLine()) != null) {
			data.append(inputLine);
		}
		reader.close();
		return data.toString();
	}

	/**
	 * get response data from request(GET method)
	 * 
	 * @param conn
	 * @throws ProtocolException
	 * @throws IOException
	 */
	public static String getGetData(HttpURLConnection conn) throws ProtocolException, IOException {
		conn.setReadTimeout(5 * 1000);
		conn.setRequestMethod("GET");
		int code = conn.getResponseCode();
		if (code != 200)
			throw new RuntimeException("request failed");
		InputStream in = conn.getInputStream();
		String ret = readStream(in);
		in.close();
		return ret;
	}

	public static final int BUF_SIZE = 4096;

	/**
	 * Read Input Stream
	 * 
	 * @param in
	 */
	private static String readStream(InputStream in) {
		char[] buf = new char[BUF_SIZE];
		int size = 0;
		StringBuilder data = new StringBuilder();
		InputStreamReader reader = new InputStreamReader(in);
		try {
			while ((size = reader.read(buf, 0, BUF_SIZE)) > 0) {
				data.append(String.copyValueOf(buf, 0, size));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return data.toString();
	}

	public static void main(String[] args) {
		// String userId = "1";
		// String path = "/home/cgli/Desktop/ico/shopping.png";
		/*
		 * File file = new File(path);
		 * System.out.println("1111111111111111111"); String ret =
		 * AppHttpUpload.uploadFile(file,
		 * userId);http://localhost:8080/pplive/v2/room/apply?owner=1
		 * 
		 * System.out.println(ret);
		 */
		String ret = "";
		String url = "http://localhost:8080/pplive/v2/room/apply?owner=1";
		// String ret = HttpUtil.sendGet(url, "","utf-8");

		 url ="http://localhost:8081/pplive/v2/room/create";
		 String json = "room={\"id\":\"76899\",\"title\":\"茵曼818大酬宾\", \"description\":\"description:Uuuuuuuuu\",\"chatId\":\"76899\",\"userId\":\"8\"}";
		
		 //destroy
		 //url ="http://localhost:8081/pplive/v2/room/destroy?roomId=76899&owner=2";
		 //json="";
	
		 
		// String param = "room="+json;
		//url = "http://119.29.166.150/v2/room/addRecording";
		//String param = "vId=200012039_c1de0fc255514bf8b7ed72690d988132&roomId=86764&userId=47";
		//url = "http://119.29.10.252/v2/room/savePushStreamUrl?roomId=76899&channelId=76899&streamUrl=http://www.test.com/xxx";
	     url="http://119.29.166.150/v2/room/addRecording";
	     json="vId=200012039_546c3648f3be41e5944f0704139061f3&roomId=43820&userId=51020&specialId=20";
		 try {
			ret = HttpUtil.sendPost(url, json, "utf-8");
			//ret = HttpUtil.sendGet(url, param, "utf-8");
			System.out.println(ret);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
